/**
 * 解析分片数据
 * @param {string} fragmentData 分片字符串（格式：序号,总片数,类型,Base64数据）
 * @returns {object} 解析后的分片信息
 */
function parseFragment(fragmentData) {
    fragmentData = fragmentData.replace(/\s+/g, '');
    const parts = fragmentData.split(',');
    if (parts.length !== 4) {
      throw new Error(`分片格式错误（需4部分，实际${parts.length}部分）`);
    }
    const index = parseInt(parts[0], 10);
    const total = parseInt(parts[1], 10);
    if (isNaN(index) || isNaN(total) || index < 1 || total < 1) {
      throw new Error(`序号/总片数无效: ${parts[0]},${parts[1]}`);
    }
  
    // 解析文件类型和文件名
    let type = parts[2].trim();
    let fileName = '';
    if (type.startsWith('file:')) {
      fileName = type.replace('file:', ''); // 提取文件名（含后缀）
      type = 'file';
    }
  
    return {
      index,
      total,
      type,
      fileName,
      data: parts[3].trim()
    };
  }
  
  /**
   * 累计分片数据
   * @param {object} fragment 当前分片
   * @param {object} storedData 已存储的分片数据
   * @returns {object} { storedData: 累计后的数据, isComplete: 是否所有分片都已接收 }
   */
  function accumulateFragment(fragment, storedData) {
    if (!storedData) {
      storedData = {
        total: fragment.total,
        type: fragment.type,
        fileName: fragment.fileName || '',
        fragments: {}
      };
    }
  
    // 校验分片匹配性
    if (storedData.total !== fragment.total || storedData.type !== fragment.type) {
      throw new Error(`分片不匹配（当前总片数=${storedData.total}，接收=${fragment.total}）`);
    }
  
    storedData.fragments[fragment.index] = fragment.data;
    const isComplete = Object.keys(storedData.fragments).length === storedData.total;
    return { storedData, isComplete };
  }
  
  /**
   * 合并所有分片
   * @param {object} storedData 累计的分片数据
   * @returns {string} 合并后的Base64字符串
   */
  function mergeFragments(storedData) {
    let mergedData = '';
    for (let i = 1; i <= storedData.total; i++) {
      if (!storedData.fragments[i]) {
        throw new Error(`缺失第${i}分片`);
      }
      mergedData += storedData.fragments[i];
    }
    return mergedData;
  }
  
  /**
   * Base64解码为二进制数据
   * @param {string} base64Data Base64字符串
   * @returns {ArrayBuffer} 二进制数据
   */
  function base64Decode(base64Data) {
    // 处理URL安全的Base64（替换-为+，_为/）
    base64Data = base64Data.replace(/-/g, '+').replace(/_/g, '/');
    // 补全Base64填充符
    const pad = base64Data.length % 4;
    if (pad) {
      base64Data += '='.repeat(4 - pad);
    }
  
    const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    const output = [];
    let i = 0;
  
    while (i < base64Data.length) {
      const enc1 = keyStr.indexOf(base64Data.charAt(i++));
      const enc2 = keyStr.indexOf(base64Data.charAt(i++));
      const enc3 = keyStr.indexOf(base64Data.charAt(i++));
      const enc4 = keyStr.indexOf(base64Data.charAt(i++));
  
      const chr1 = (enc1 << 2) | (enc2 >> 4);
      const chr2 = ((enc2 & 0x0F) << 4) | (enc3 >> 2);
      const chr3 = ((enc3 & 0x03) << 6) | enc4;
  
      output.push(chr1);
      if (enc3 !== 64) output.push(chr2);
      if (enc4 !== 64) output.push(chr3);
    }
  
    return new Uint8Array(output).buffer;
  }
  
  module.exports = {
    parseFragment,
    accumulateFragment,
    mergeFragments,
    base64Decode
  };